<?php


namespace app\user\model;

use app\common\model\SendLog;
use think\facade\Validate;


class Login
{
    public static function login($data,$checkCaptcha=0){
        $type=isset($data['login_type'])?$data['login_type']:'default';
        switch ($type){
            case 'code';
                $res=static::codeLogin($data);
                break;
            default:
                $res=static::defaultLogin($data,$checkCaptcha);
                break;
        }
        if(!$res['code']){
            return $res;
        }
        $loginIp=request()->ip();
        unset($data['password']);
        UserLoginLog::create([
            'ip'=>$loginIp,
            'request'=>json_encode($data),
            'code'=>$res['code'],
            'msg'=>$res['msg']
        ]);

        if($res['code']==1){
            $userId=$res['data']['id'];
            (new User())->where('id',$userId)->save([
                'last_login_ip'=>$loginIp,
                'last_login_time'=>time(),
            ]);
            $loginScore=sysconfig('score.login_award');
            if($loginScore){
                $rewardCount=UserRichesLog::where('create_time','>',todayTime())
                    ->where('user_id',$userId)
                    ->where('subject','LOGIN')
                    ->count();
                if(!$rewardCount) {
                    UserRichesLog::note($loginScore,$userId, '登录获系统奖励', 1, 0, 'LOGIN');
                }
            }
            session('userid', $userId);
            cookie('userid', $userId,30*86400);
        }
        return $res;
    }

    private static function defaultLogin($data,$needCheckCaptcha=1){
        //必填项
        $only=['object', 'password'];
        $rule = [
            'object|用户名'      => 'require|length:4,30',
            'password|密码'       => 'require',
        ];
        $ret=validate_ext($only,$rule,$needCheckCaptcha,$data);
        if(isset($ret['code'])&&$ret['code']==0){
            return $ret;
        }
        $userstr = $ret['object'];
        $userModel = new User();
        //用户名、邮箱、手机号均可登陆
        if (preg_match("/^1[3-9]\d{9}$/", $userstr)) {
            $map['mobile'] = $userstr;
        } elseif (Validate::is($userstr, 'email')) {
            $map['email'] = $userstr;
        } else {
            $map['username'] = $userstr;
        }
        $user = $userModel->where($map)->find();
        if (!$user||$user['password'] != md5($data['password'] . $user['salt'])) {
            return array('code' => 0, 'msg' => '账号或密码错误', 'data' => []);
        }
        if($user['status']!=1){
            return array('code' => 0, 'msg' => '账号被限制登录', 'data' => []);
        }
        return array('code'=>1,'data'=>$user,'msg'=>'登录成功');
    }

    private static function codeLogin($data){

        $only=['object', 'sms_code'];
        $rule = [
            'sms_code|验证码'       => 'require',
        ];
        $ret=validate_ext($only,$rule,0,$data);
        if(isset($ret['code'])&&$ret['code']==0){
            return $ret;
        }

        $object=$ret['object'];

        $userModel = new User();
        $objectType = checkIsPhoneOrEmail($object,3);
        if (!$objectType) {
            return array('code' => -1, 'msg' => '用户名格式不正确', 'data' => []);
        }
        if ($objectType == 2) {
            $map['mobile'] = $object;
        } else {
            $map['email'] = $object;
        }
        $res = SendLog::codeCheck($ret['sms_code'], $object,$objectType,'LOGIN');
        if ($res['code'] != 1) {
            return $res;
        }

        $user = $userModel->where($map)->find();
        if (!$user) {
            //新注册的
            $user=User::createNew($map);
        }else if($user['status']!=1){
            return array('code' => 0, 'msg' => '账号被限制登录', 'data' => []);
        }
        SendLog::codeSetUsed($res['data']['id']);
        return array('code'=>1,'data'=>$user,'msg'=>'登录成功');

    }
}
